package gitee.derumin.lifeissohard.mixin;

import gitee.derumin.lifeissohard.lishhungersystem.LishHungerManager;
import net.minecraft.advancement.criterion.ConsumeItemCriterion;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.item.PotionItem;
import net.minecraft.server.network.ServerPlayerEntity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;

@Mixin(PotionItem.class)
public abstract class PotionItemMixin extends Item {

    public PotionItemMixin(Settings settings) {
        super(settings);
    }

    @Redirect(method = "finishUsing" , at = @At(value = "INVOKE" , target = "Lnet/minecraft/entity/player/PlayerInventory;insertStack(Lnet/minecraft/item/ItemStack;)Z"))
    private boolean cancel(PlayerInventory instance, ItemStack stack){
        return false;
    }

    @Redirect(method = "finishUsing" , at = @At(value = "INVOKE" , target = "Lnet/minecraft/entity/player/PlayerEntity;getInventory()Lnet/minecraft/entity/player/PlayerInventory;"))
    private PlayerInventory returnGlassBottle(PlayerEntity instance){
        ItemStack itemStack = new ItemStack(Items.GLASS_BOTTLE);
        if (!instance.getInventory().insertStack(itemStack)) {
            instance.dropItem(itemStack, false);
        }
        return instance.getInventory();
    }

    @Redirect(method = "finishUsing" , at = @At(value = "INVOKE" , target = "Lnet/minecraft/advancement/criterion/ConsumeItemCriterion;trigger(Lnet/minecraft/server/network/ServerPlayerEntity;Lnet/minecraft/item/ItemStack;)V"))
    private void playerDrinkPotion(ConsumeItemCriterion instance, ServerPlayerEntity player, ItemStack stack){
        instance.trigger(player,stack);
        if (player.getHungerManager() instanceof LishHungerManager lishHungerManager) {
            String potionName = stack.getNbt() == null ? "empty" : stack.getNbt().getString("Potion");
            if (potionName.equalsIgnoreCase("empty") || potionName.equalsIgnoreCase("minecraft:water") || potionName.equalsIgnoreCase("minecraft:mundane") || potionName.equalsIgnoreCase("minecraft:thick")){
                lishHungerManager.drink("water_in_bottle");
            }else lishHungerManager.drink("potions_with_metal");
        }
    }
}
